<?php

namespace App\Http\Controllers\V1\Api;

use App\Http\Requests\Api\CoinServer;
use App\Models\V1\Coin;
use App\Models\V1\Community;

use App\Models\V1\Goods;
use App\Models\V1\Opinion;
use App\Models\V1\OpinionClass;

use App\Models\V1\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class CoinController extends BaseController
{

    /**
     * 用户发表意见
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function Add(CoinServer $request)
    {
        $request->validate('v1.create');
        $user = auth('box')->user();


        $goods_id = $request->input('goods_id');
        $leave = $request->input('leave');
        $num = $request->input('num');

        $goods = Goods::where('id', $goods_id)->first()->toArray();
        $u_integral = $goods['integral'] * $num;

        if ($u_integral > $user['integral']) {
            return ajax_output(300, "米米不够");
        }


        $community_name = Community::where('id', $user['community_id'])->value('name');


        $model = new Coin();
        try {
            DB::beginTransaction();
            $model->create([

                'user_id' => $user['id'],
                'user_name' => $user['username'],
                'mobile' => $user['mobile'],

                'goods_id' => $goods_id,
                'goods_name' => $goods['title'],

                'community_id' => $user['community_id'],
                'community_name' => $community_name,
                'num' => $num,

                'integral' => $goods['integral'],
                'fmimi' => $user['integral'],
                'bmimi' => $user['integral'] - $u_integral,

                'leave' => $leave,

            ]);

            Users::where('id',$user['id'])->decrement('integral', $u_integral);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return ajax_output(300, "数据异常:" . $e->getMessage());
        }
        return ajax_output(200, "成功");
    }


}
